<?php
declare (strict_types=1);

namespace app\scan_bag\controller;

use app\admin\model\advertiser\AdvertiserTask;
use app\admin\model\advertiser\AdvertiserTaskLog;
use app\admin\model\advertiser\AdvertiserThird;
use app\admin\model\advertiser\AdvertiserThirdLog;
use app\admin\model\base\User;
use app\admin\model\base\UserOfficial;
use app\admin\model\iot\AdvertiserTaskDevice;
use app\admin\model\iot\ScanBagDay;
use app\admin\model\iot\ScanBagWay;
use app\admin\service\base\JwtService;
use app\BaseController;
use app\BaseService;
use app\scan_bag\service\ScanBagV1Service;
use app\scan_bag\service\ScanBagV2Service;
use app\scan_bag\service\V1_Way_1_0Service;
use think\App;
use think\facade\Cache;
use think\facade\Log;
use think\response\Json;
use wechat\ScanBagMiniProgram;
use wechat\WsOfficialAccount;
use wechat\WsOpenPlatform;
use app\admin\model\base\UserSubscribeWorkWx;
use wechat\WsWork;

/**
 * 微信LCV3_2扫码取袋
 */
class LCV3_2 extends BaseController
{

    /**
     * 当前扫码路径
     * @var string
     */
    private string $way = 'LCV3_2';

    /**
     * 微信H5用户登录
     * @param ScanBagV2Service $scanBagV2Service
     * @return Json
     */
    public function wechatLogin(ScanBagV2Service $scanBagV2Service): Json
    {
        //接受参数
        $code = $this->request->param('code/s', '');
        //微信解析code
        $bool = $scanBagV2Service->wechatH5Login2($code);
        if ($bool['bool']) {
            //签发token
            $jst_data = JwtService::authorizations('scan_bag', $bool['user_id'], 3600);
            if ($jst_data['bool']) {
                return jsonReturn(1, $bool, '登录成功');
            }
        }
        return jsonReturn(0, [], '签发token失败');
    }

    /**
     * 微信H5用户取袋次数
     * @return Json
     */
    public function userScanNum(): Json
    {
        $user_id = WS_USER_ID;
        $day = ScanBagDay::getUserIdDayNum($user_id);
        $mac_id = $this->request->param('mac_id', '');
        if (!$mac_id) {
            return jsonReturn(0, [], '参数错误');
        }
        //标记取袋安全码
        $SafeCode = ScanBagV2Service::getBagOutSafeCode($user_id, $this->way, $mac_id, 1);
        return jsonReturn(1, $day);
    }

    /**
     * 获取JSAPI配置
     * @return Json
     */
    public function jsApiConfig(): Json
    {
        //接受参数
        $url = $this->request->param('url/s', '');
        $obj = new WsOfficialAccount();
        $data = $obj->getJsApi($url);;
        return jsonReturn(1, $data);
    }

    /**
     * 获取推广微信小程序
     * @return Json
     */
    public function getWechatApplet(): Json
    {
        //接收参数
        $user_id = WS_USER_ID;
        $mac_id = $this->request->param('mac_id', '');
        if (!$mac_id) {
            return jsonReturn(0, [], '参数错误');
        }
        //通过mac_id获取路径
        $WayInfo = ScanBagWay::getMacIdWay($mac_id);
        if ($WayInfo['key'] != $this->way) {
            return jsonReturn(0, [], '当前设备路径错误,请联系管理员!');
        }
        //判断需要验证取袋路径
        if ($WayInfo and $WayInfo['third_mini']) {
            //获取推广小程序信息
            $Third = AdvertiserThird::getIDThird($WayInfo['third_mini']);
            if ($Third and !in_array($mac_id, $Third['prohibit']) and $Third['mini_ogh'] and $Third['mini_appid']) {
                $temp = [
                    'way' => $WayInfo['key'],
                    'third_id' => $Third['id'],
                    'type' => $Third['type'],
                    'mini_name' => $Third['mini_name'],
                    'mini_ogh' => $Third['mini_ogh'],
                    'mini_appid' => $Third['mini_appid'],
                    'mini_link' => $Third['mini_link'],
                ];
                //写入统计
                AdvertiserThirdLog::writeMiniprogramLog($user_id, $Third['id'], $mac_id);
                //标记取袋安全码
                $SafeCode = ScanBagV2Service::getBagOutSafeCode($user_id, $this->way, $mac_id, 2);
                if (!$SafeCode) {
                    return jsonReturn(0, [], '请重新扫描屏幕上的二维码');
                }
                return jsonReturn(1, $temp);
            }
        }
        return jsonReturn(0, [], '路径参数错误');
    }

    /**
     * 获取微信H5公众号二维码
     * @return Json
     */
    public function wechatQrcode(): Json
    {
        //默认值
        $user_id = WS_USER_ID;
        $name = $appid = $qrcode = '';
        $is_qrcode = false;
        //接受参数
        $meipaopenid = $this->request->param('meipaopenid/s', '');
        $lsId = $this->request->param('lsId/s', '');
        $mac_id = $this->request->param('mac_id/s', '');
        if (!$mac_id) {
            return jsonReturn(0, [], '设备参数错误,请联系管理员!');
        }
        //对接聚合平台
        $WayInfo = ScanBagWay::getPathKeyWay($this->way);
        if (!$WayInfo or $WayInfo['key'] != $this->way) {
            return jsonReturn(0, [], '当前设备路径错误,请联系管理员!');
        }
        $advertiser_third =[1,4,6];
        $OfficialAccount=[];
        $linsu_auth =0;
        foreach($advertiser_third as $v){

            if($v==1 && empty($lsId)){
                $OfficialAccount = AdvertiserThird::getIdOfficialAccount($user_id, $v, $mac_id);
            }
            if($v==4 && empty($lsId)){
                $OfficialAccount = AdvertiserThird::getIdOfficialAccount($user_id, $v, $mac_id);
            }
            if($v==6 && empty($lsId)){
                $OfficialAccount = AdvertiserThird::getIdOfficialAccount($user_id, 6, $mac_id, $meipaopenid);
                if(!$OfficialAccount){
                    $linsu_auth =1;
                }
            }
            if ($OfficialAccount) {
                break 1;
            }
        }

        if ($OfficialAccount) {
            $name = $OfficialAccount['name'];
            $appid = $OfficialAccount['appid'];
            $qrcode = $OfficialAccount['qrcode'];
            $is_qrcode = $OfficialAccount['is_qrcode'];
        } else {
            //没拿到时则获取设置的第三方平台
            $OfficialAccount = AdvertiserThird::getIdOfficialAccount($user_id, $WayInfo['third_official'], $mac_id);
            if ($OfficialAccount) {
                $name = $OfficialAccount['name'];
                $appid = $OfficialAccount['appid'];
                $qrcode = $OfficialAccount['qrcode'];
                $is_qrcode = $OfficialAccount['is_qrcode'];
            }
        }
        if (!$name or !$appid or !$qrcode) {
            try {
                $type = 1;
                $tasks = AdvertiserTask::wechatTaskDistributionNew($type);
                if ($tasks) {
                    foreach($tasks as $task){
                        //判断是否有限制设备
                        $adAdvertiserTaskDevice=AdvertiserTaskDevice::where('task_id',$task['id'])->column('mac_id');
                        if($adAdvertiserTaskDevice && !in_array($mac_id,$adAdvertiserTaskDevice)){
                            continue ;
                        }
                        //判断是否有关注
                        $exist = UserOfficial::itExist($user_id, $task['appid']);
                        if(!$exist){
                            $name = $task['name'];
                            $appid = $task['appid'];
                            UserOfficial::oneLogSave($user_id, $appid, 1);
                            //获取带参数的二维码url
                            $Ws = new WsOpenPlatform();
                            $qrcode = $Ws->officialAccountTemporaryQrcode($task['appid'], 'scan_bag');
                            //写入推广任务明细记录
                            AdvertiserTaskLog::writeTaskLog($user_id, $mac_id, intval($task['id']), floatval($task['single_price']));
                            break ;
                        }

                    }

                }//end if
            } catch (Exception $exception) {
                Log::write($exception->getMessage(), '广告主微信H5公众号二维码');
            }
        }//end if
        $is_work_wx =0;
        //显示企业微信用户二维码
        if(!$name or !$appid or !$qrcode){
            $WsWork = new WsWork();
            $qrcode = "https://work.weixin.qq.com/u/vc5f497b8ae4a88aea?v=4.0.8.19699";
            $is_work_wx=1;
        }
        //没有关注和没有第三方二维码则显示兜底二维码
        if (!$qrcode) {
            $sys_config = config('sys_config.WsOfficialAccount');
            //未关注默认主体公众号二维码
            $name = $sys_config['name'];
            $appid = $sys_config['appid'];
            //获取带参数的二维码url
            $Ws = new WsOfficialAccount();
            $qrcode = $Ws->temporaryQrcode('scan_bag');
        }
        //返回数据
        $data = ['name' => $name, 'appid' => $appid, 'qrcode' => $qrcode, 'is_qrcode' => $is_qrcode,'linsu_auth'=>$linsu_auth,'is_work_wx'=>$is_work_wx];
        return jsonReturn(1, $data);
    }

    /**
     * 微信上传经纬度信息
     * @param V1_Way_1_0Service $v1_Way_1_0Service
     * @return Json
     */
    public function wechatLatLon(V1_Way_1_0Service $v1_Way_1_0Service): Json
    {
        //接受参数
        $mac_id = $this->request->param('mac_id/s', '0');
        $latitude = $this->request->param('latitude/s', '0');
        $longitude = $this->request->param('longitude/s', '0');
        $accuracy = $this->request->param('accuracy/d', 0);    //位置精度
        //经纬度保存数据库
        $user_id = WS_USER_ID;
        //把地理位置信息保存至用户表
        User::userLocationRedis($user_id, $mac_id, $latitude, $longitude);
        //微信验证上传经纬度信息
        $bool = $v1_Way_1_0Service->wechatLatLon($mac_id, $latitude, $longitude);
        if ($bool) {
            return jsonReturn(1, [], '验证通过');
        }
        return jsonReturn(0, [], '您的位置距离设备太远,请移步设备前扫码免费领取。');
    }

    /**
     * 微信H5识别二维码
     * @return Json
     */
    public function qrcodeDiscern(): Json
    {
        //接受参数
        $user_id = WS_USER_ID;
        $mac_id = $this->request->param('mac_id/s');
        if (!$mac_id) {
            return jsonReturn(0, [], 'MacID参数错误');
        }
        //标记取袋安全码
        $SafeCode = ScanBagV2Service::getBagOutSafeCode($user_id, $this->way, $mac_id, 2);
        if (!$SafeCode) {
            return jsonReturn(0, [], '请重新扫描屏幕上的二维码');
        }
        return jsonReturn(1, []);
    }

    /**
     * 微信小程序URLScheme
     * @return Json
     */
    public function getURLScheme(): Json
    {
        //接收参数
        $params = $this->request->param();
        if (!isset($params['mac_id']) or !$params['mac_id']) {
            return jsonReturn(0, [], '设备参数错误,请联系管理员!');
        }
        //获取用户信息
        $user_id = WS_USER_ID;
        //标记取袋安全码
//        $SafeCode = ScanBagV2Service::getBagOutSafeCode($user_id, $this->way, $params['mac_id'], 3,true);
//        if (!$SafeCode) {
//            return jsonReturn(0, [], '请重新扫描屏幕上的二维码');
//        }
        $User = User::getIdUserInfo($user_id);
        $params['open_id'] = $User['openid'];
        //获取次数
        $WayInfo =json_decode(Cache::get(BaseService::generateScanBagStrategyKey($user_id)),true);
        if ($WayInfo['key'] != $this->way) {
            return jsonReturn(0, [], '路径参数错误,请联系管理员');
        }
        //生成取袋路径微信小程序码
        $wechat = new ScanBagMiniProgram($WayInfo);
        $path = $WayInfo['mini_link'] ?? 'pages/index/index';
        //增加取袋码
        $params['way'] = $WayInfo['key'];
        $SafeCode = ScanBagV2Service::getBagOutSafeCode($user_id, $this->way, $params['mac_id'], 3,true);
        if (!$SafeCode) {
            $params['waycode'] = rand(100000,999999);
        }else{
            $params['waycode'] = ScanBagV2Service::generateBagOutWaycode($User, $WayInfo['key'], $params['mac_id']);
        }
        $params['success_redirect_uri']=$WayInfo['success_redirect_uri']??'';
        //收到打开时需要的参数
        $data['miniPath'] = $path . '?' . http_build_query(array_unique($params));
        //则生成取袋路径微信小程序码
        $data['scheme'] = $wechat->URLScheme($path, http_build_query($params));
        $code = $data['scheme']['bool'] ? 1 : 0;
        return jsonReturn($code, $data);
    }

    /**
     * 微信取袋码出袋
     * @return Json
     */
    public function postOutBag(): Json
    {
        //接收参数
        $user_id = WS_USER_ID;
        $User = User::getIdUserInfo($user_id);
        $mac_id = $this->request->param('mac_id/s', '');
        //获取次数
        $WayInfo =json_decode(Cache::get(BaseService::generateScanBagStrategyKey($user_id)),true);
        if ($WayInfo['key'] != $this->way) {
            return jsonReturn(0, [], '路径参数错误,请联系管理员');
        }
        $waycode = ScanBagV2Service::generateBagOutWaycode($User, $WayInfo['key'], $mac_id);
        $location_limit = $this->request->param('location_limit/d', 0);
        //判断缓存是否有策略
        $tKey = BaseService::generateScanBagStrategyKey($user_id);
        $WayInfo = Cache::get($tKey);
        if($WayInfo){
            $location_limit = json_decode($WayInfo,true)['location_limit'];
        }
        //判断参数
        if (!$user_id or !$mac_id or !$waycode) {
            return jsonReturn(0, [], '参数错误');
        }
        //标记取袋安全码
        $SafeCode = ScanBagV2Service::getBagOutSafeCode($user_id, $this->way, $mac_id, 2, true);
        if (!$SafeCode) {
            return jsonReturn(0, [], '请重新扫描设备二维码!');
        }
        if($location_limit){
            //获取缓存当前用户经纬度
            $LatLon = Cache::get(BaseService::generateLocationKey($user_id));
            if (!$LatLon or !isset($LatLon['latitude']) or !isset($LatLon['longitude'])) {
                return jsonReturn(0, [], '您的位置授权失败,请重新扫描设备二维码!');
            }
            //验证地理位置
            $bool = ScanBagV2Service::verifyLatLon($mac_id, $LatLon['latitude'], $LatLon['longitude']);
            if (!$bool) {
                return jsonReturn(0, [], '您的位置距离设备太远,请移步设备前扫码免费领取!');
            }
        }
        //执行出袋程序
        $res = ScanBagV2Service::bagOutProgram($waycode, $this->way, $user_id, $mac_id,1);
        if ($res['bool']) {
            return jsonReturn(1, $res['data'], $res['msg']);
        }
        return jsonReturn(0, [], $res['msg']);
    }

    /**
     * 发起微信支付
     * @param ScanBagV1Service $scanBagV1Service
     * @return Json
     */
    public function wechatPayOrder(ScanBagV1Service $scanBagV1Service): Json
    {
        $user_id = WS_USER_ID;
        $mac_id = $this->request->param('mac_id');
        if (!$mac_id) {
            return jsonReturn(0, [], '设备信息错误');
        }
        return $scanBagV1Service->payOrderToV1($user_id, $mac_id);
    }

    /**
     * 判断是否打开位置限制
     * @return Json
     */
    public function locationLimit():Json
    {
        $mac_id = $this->request->param('mac_id/s','');
        //判断参数
        if (!$mac_id) {
            return jsonReturn(0, [], '参数错误');
        }
        //通过mac_id获取路径
        $WayInfo = ScanBagWay::getMacIdWay($mac_id);
        if($WayInfo && $WayInfo['location_limit']){
            return jsonReturn(1, ['location_limit'=>$WayInfo['location_limit']]);
        }
        return jsonReturn(1, ['location_limit'=>0]);
    }

    public function isWorkWxSubscribe():Json
    {
        $User = User::getIdUserInfo(WS_USER_ID);
        //判断参数
        $check =UserSubscribeWorkWx::itSubscribe($User['unionid']);
        if($check){
            return jsonReturn(1, ['work_wx_subscribe'=>1]);
        }
        return jsonReturn(1, ['work_wx_subscribe'=>0]);
    }

}
